import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Input, Button, Field, Form, Upload, Message } from '@teamix/ui';
import AccessSelect from 'components/accessSelect/setting';
import { defaultPictureSize } from 'utils/constants.js';
import { getPathWithRootPath } from 'utils/router';
import debounce from 'lodash.debounce';
import { checkGroupNamePath } from 'api/index.js';

// id通过force取得
import intl from '../../../../../../../../../../locale';

const { pathResource } = window.FORCE;

const FormItem = Form.Item;
const formItemLayout = {
  labelCol: {
    span: 6,
  },

  wrapperCol: {
    span: 14,
  },
};

export default class BaseForm extends Component {
  static propTypes = {
    saveGeneral: PropTypes.func,
    name: PropTypes.string,
    path: PropTypes.string,
    id: PropTypes.number,
    description: PropTypes.string,
    visibilityLevel: PropTypes.number,
    avatarUrl: PropTypes.string,
    namespaceVisibilityLevel: PropTypes.number,
  };

  static defaultProps = {
    saveGeneral: () => {},
    name: null,
    path: null,
    id: 0,
    description: null,
    visibilityLevel: 0,
    namespaceVisibilityLevel: 0,
    avatarUrl: null,
  };

  constructor(props) {
    super(props);
    this.field = new Field(this);
    const { avatarUrl } = props;
    const fileList = [];
    if (avatarUrl) {
      fileList.push({
        uid: '0',
        name: this.getAvatarName(avatarUrl),
        state: 'done',
        size: defaultPictureSize,
        downloadUrl: avatarUrl,
        url: avatarUrl,
        imgUrl: avatarUrl,
      });
    }
    this.state = {
      submitting: false,
      fileList,
    };

    this.checkName = debounce(this.checkName, 500);
  }

  checkName(value, callback) {
    checkGroupNamePath({ name: value, namespace_id: pathResource.parentId })
      .then(() => {
        callback();
      })
      .catch((err) => {
        if (err.responseText) {
          const errCause = JSON.parse(err.responseText).cause;
          callback(`${errCause}`);
        } else {
          throw err;
        }
      });
  }

  componentDidMount() {
    // this.initData();
  }

  handleChangeAccess = (value) => {
    this.field.setValue('visibility_level', value);
  };

  nameValidator = (rule, value, callback) => {
    const { name } = this.props;
    if (!value || value === name) {
      callback();
      return;
    }
    if (value.length > 100) {
      callback(
        intl.get({
          id: 'code-assets.containers.baseForm.TheLengthCannotExceed',
          defaultMessage: '长度不能超过100',
        }),
      );
      return;
    }
    if (/^[a-zA-Z0-9_.][a-zA-Z0-9_.-]{0,}$/.test(value)) {
      this.checkName(value, callback);
    } else {
      callback(
        intl.get({
          id: 'code-assets.containers.baseForm.ItCanOnlyContainLowercase',
          defaultMessage: "只能包含小写字母和数字、 '_'、'.'和'-'，且只能以小写字母、数字或'_'开头",
        }),
      );
    }
  };

  visibilityLevelCanBeEdited() {
    const { role = '' } = pathResource;
    return ['ORG_ADMIN', 'ORG_OWNER', 'ADMIN', 'MASTER', 'OWNER'].indexOf(role) > -1;
  }

  saveChanges = () => {
    if (this.state.submitting) return;
    this.setState({ submitting: true });
    this.field.validate((errors) => {
      if (!errors) {
        const formData = this.field.getValues();
        if (this.state.fileList && this.state.fileList.length === 1) {
          formData.avatar_url = this.state.fileList[0].imgUrl;
        } else {
          formData.avatar_url = '';
        }
        this.props.saveGeneral(formData, (result) => {
          this.setState({ submitting: result });
        });
      } else {
        this.setState({ submitting: false });
      }
    });
  };

  getAvatarName = (url) => {
    return url && url.match(/.*\/(.*)/) ? url.match(/.*\/(.*)/)[1] : url;
  };

  onUploadChange = (files) => {
    if (files && !files.length) {
      this.setState({
        fileList: [],
      });
    }
  };

  uploadError = (f) => {
    Message.warning({
      title:
        f.message ||
        intl.get({
          id: 'code-assets.containers.baseForm.UnableToUploadTheAvatar',
          defaultMessage: '头像上传失败',
        }),
    });

    const { fileList } = this.state;
    if (fileList.length === 0) {
      this.changeAvatarUrl(null);
    } else {
      this.changeAvatarUrl(fileList[0]);
    }
  };

  uploadSuccess = (res, file) => {
    if (res && res.response && res.response.code === '0') {
      // Message.success({
      //   title: '头像上传成功',
      // });
      this.changeAvatarUrl(file[0]);
    } else {
      Message.error({
        title: intl.get({
          id: 'code-assets.containers.baseForm.UnableToUploadTheAvatar',
          defaultMessage: '头像上传失败',
        }),
      });
    }
  };

  changeAvatarUrl = (file) => {
    const newfileList = !file
      ? []
      : [
          {
            name: file.name,
            state: file.state,
            size: file.size,
            imgUrl: file.imgUrl || (file.response ? file.response.imgUrl : ''),
            url: file.imgUrl || (file.response ? file.response.imgUrl : ''),
            downloadUrl: file.downloadUrl || (file.response ? file.response.downloadUrl : ''),
          },
        ];

    this.setState({
      fileList: newfileList,
    });
  };

  render() {
    const { init } = this.field;
    const { name, description, visibilityLevel } = this.props;
    const { id } = pathResource;
    const { fileList } = this.state;

    // TODO 可见性：1. 受企业调整公开性限制 改成组 2. 受子组和库公开性限制：公开->私有，若子组和库存在公开不可调整
    return (
      <div className="base-form">
        <Form {...formItemLayout} field={this.field} labelAlign="top">
          <div className="form-top">
            <div className="group-image-wrapper">
              <Upload.Card
                listType="card"
                action={getPathWithRootPath(`/api/v3/common/image?group_id=${id}&type=avatar${
                  window.FORCE.csrfTokenName
                    ? `&${window.FORCE.csrfTokenName}=${window.FORCE.csrfToken}`
                    : ''
                }`)}
                accept="image/png, image/jpg, image/jpeg, image/gif, image/bmp"
                onChange={this.onUploadChange}
                onSuccess={this.uploadSuccess}
                onError={this.uploadError}
                className="group-image-upload"
                value={fileList}
                limit={1}
              />
            </div>
            <div className="group-name-wrapper">
              <FormItem
                label={intl.get({
                  id: 'code-assets.containers.baseForm.CodeGroupName',
                  defaultMessage: '代码组名称',
                })}
                required
              >
                <Input
                  placeholder={intl.get({
                    id: 'code-assets.containers.baseForm.EnterACodeGroupName',
                    defaultMessage: '请输入代码组名称',
                  })}
                  spellCheck={false}
                  maxLength={100}
                  hasLimitHint
                  {...init('name', {
                    initValue: name,
                    rules: [
                      {
                        required: true,
                        message: intl.get({
                          id: 'code-assets.containers.baseForm.ThisParameterIsRequired',
                          defaultMessage: '该项为必填项',
                        }),
                      },

                      {
                        validator: this.nameValidator,
                      },
                    ],
                  })}
                />
              </FormItem>
            </div>
          </div>

          <FormItem
            label={intl.get({
              id: 'code-assets.containers.baseForm.Description',
              defaultMessage: '代码组描述',
            })}
          >
            <Input.TextArea
              placeholder={intl.get({
                id: 'code-assets.containers.baseForm.EnterADescriptionOfThe',
                defaultMessage: '请输入代码组描述',
              })}
              spellCheck={false}
              {...init('description', { initValue: description })}
            />
          </FormItem>
          <FormItem
            required
            label={
              <span>
                {intl.get({
                  id: 'code-assets.containers.baseForm.Openness',
                  defaultMessage: '公开性',
                })}
              </span>
            }
          >
            <AccessSelect
              {...init('visibility_level', {
                initValue: Number(visibilityLevel),
              })}
              disabled={!this.visibilityLevelCanBeEdited()}
              onChange={this.handleChangeAccess}
              style={{ width: '300px' }}
              pathResourceId={id}
              isRepo={false}
              id="group-setting-visibility-level"
            />
          </FormItem>
          <FormItem className="no-mr-b">
            <Button type="primary" loading={this.state.submitting} onClick={this.saveChanges}>
              {intl.get({ id: 'code-assets.containers.baseForm.Save', defaultMessage: '保存' })}
            </Button>
          </FormItem>
        </Form>
      </div>
    );
  }
}
